package com.unicloud.medical.oss.core;

import com.unicloud.medical.oss.common.OSSService;
import com.unicloud.medical.oss.common.enums.ErrorEnum;
import com.unisound.medical.common.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class OSSServiceFinder implements ApplicationContextAware, InitializingBean {
    private ApplicationContext context;

    private Map<String, OSSService> finder = new HashMap<>();

    public OSSService find(String name) {
        AssertUtil.assertTrue(StringUtils.isNotEmpty(name), ErrorEnum.OSS_NAME_INVALID);
        OSSService ossService = finder.get(name.toLowerCase());
        AssertUtil.assertTrue(Objects.nonNull(ossService), ErrorEnum.OSS_NAME_INVALID);
        return ossService;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, OSSService> ossServiceMap = context.getBeansOfType(OSSService.class);
        if (MapUtils.isEmpty(ossServiceMap)) {
            log.warn("OSS存储服务没有发现提供者");
        } else {
            ossServiceMap.forEach((name, ossService) -> finder.put(ossService.name().toLowerCase(), ossService));
        }
    }
}
